package edu.worldskills.snake2;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SnakeGameView extends View {
    private static final String TAG = "SnakeGameView";
    private static final int CELL_SIZE = 60; // 单元格大小
    private static final int NUM_CELLS_X = 35; // 横向单元格数
    private static final int NUM_CELLS_Y = 27; // 纵向单元格数


    private List<int[]> snake; // 蛇的身体坐标列表
    private int[] food; // 食物坐标【x,y】
    private int direction = 3; // 初始方向：0上、1下、2左、3右

    private Paint snakePaint, foodPaint, bgPaint, textPaint, controlPaint, buttonPaint;

    Handler handler;
    private Runnable gameLoop;

    private float lastX, lastY; // 记录触摸坐标

    private boolean isGameOver = false;

    private boolean isRuning = false;

    int second = 0;
    int score = 0;

    private Rect startButton, pauseButton, restartButton,stopButton, backButton;

    public SnakeGameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        snakePaint = new Paint();
        snakePaint.setColor(Color.GREEN);

        foodPaint = new Paint();
        foodPaint.setColor(Color.RED);

        bgPaint = new Paint();
        bgPaint.setColor(Color.BLACK);

        controlPaint = new Paint();
        controlPaint.setColor(Color.GRAY);


        textPaint = new Paint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(40);
        textPaint.setTextAlign(Paint.Align.CENTER);

        snake = new ArrayList<>();
        snake.add(new int[]{0, 0}); // 初始蛇头

        buttonPaint = new Paint();
        buttonPaint.setColor(Color.BLACK);

        spawnFood();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawRect(0, 0, 2100, 1640, bgPaint);
        canvas.drawRect(2100, 0, 2560, 1640, controlPaint);

        int buttonWidth = 360;  // (2560 - 2100) = 460, leaving some margin
        int buttonHeight = 120;
        int startX = 2150;  // 2100 + 50 (left margin)
        int startY = 640;   // Some top margin
        int verticalGap = 50;  // Gap between buttons


//        时间和得分
        canvas.drawText("Second:" + second / 1000, startX + 100, startY - 400, textPaint);
        canvas.drawText("Score:" + score, startX + 100, startY - 300, textPaint);

//确定按钮的位置
        startButton = new Rect(startX, startY, startX + buttonWidth, startY + buttonHeight);
        pauseButton = new Rect(startX, startY + buttonHeight + verticalGap,
                startX + buttonWidth, startY + 2 * buttonHeight + verticalGap);
        restartButton = new Rect(startX, startY + 2 * (buttonHeight + verticalGap),
                startX + buttonWidth, startY + 3 * buttonHeight + 2 * verticalGap);

        stopButton = new Rect(startX, startY + 3 * (buttonHeight + verticalGap),
                startX + buttonWidth, startY + 4 * buttonHeight + 3 * verticalGap);

        backButton = new Rect(startX, startY + 4 * (buttonHeight + verticalGap),
                startX + buttonWidth, startY + 5* buttonHeight + 4 * verticalGap);


//绘制按钮
        canvas.drawRect(startButton, buttonPaint);
        canvas.drawText("start", startX + buttonWidth / 2, startY + buttonHeight / 2, textPaint);


        canvas.drawRect(pauseButton, buttonPaint);
        canvas.drawText("pause", startX + buttonWidth / 2, startY + buttonHeight + verticalGap + buttonHeight / 2, textPaint);

        canvas.drawRect(restartButton, buttonPaint);
        canvas.drawText("restart", startX + buttonWidth / 2, startY + 2 * (buttonHeight + verticalGap) + buttonHeight / 2, textPaint);


        canvas.drawRect(stopButton, buttonPaint);
        canvas.drawText("stop", startX + buttonWidth / 2, startY + 3 * (buttonHeight + verticalGap) + buttonHeight / 2, textPaint);


        canvas.drawRect(backButton, buttonPaint);
        canvas.drawText("back", startX + buttonWidth / 2, startY + 4 * (buttonHeight + verticalGap) + buttonHeight / 2, textPaint);


//        绘制蛇、食物；
        for (int[] part : snake) {
            canvas.drawRect(part[0] * CELL_SIZE, part[1] * CELL_SIZE,
                    (part[0] + 1) * CELL_SIZE, (part[1] + 1) * CELL_SIZE, snakePaint);
        }

        canvas.drawRect(food[0] * CELL_SIZE, food[1] * CELL_SIZE,
                (food[0] + 1) * CELL_SIZE, (food[1] + 1) * CELL_SIZE, foodPaint);

        if (isGameOver) {
            canvas.drawText("游戏结束", getWidth() / 4, getHeight() / 2, textPaint);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            float x = event.getX();
            float y = event.getY();
            //为按钮添加单击事件
            if (startButton.contains((int) x, (int) y)) {
                //避免再次单击start越来越快
                if (isRuning) {
                    return true;
                }

                start();
                isRuning = !isRuning;
                Log.d(TAG, "start");
                return true;
            } else if (pauseButton.contains((int) x, (int) y)) {
                pause();
                Log.d(TAG, "pause");
                return true;
            } else if (restartButton.contains((int) x, (int) y)) {
                restart();
                Log.d(TAG, "restart");
                return true;
            } else if (stopButton.contains((int) x, (int) y)) {
                stop();
                Log.d(TAG, "stop");
                return true;
            }else if (backButton.contains((int) x, (int) y)) {
                back();
                Log.d(TAG, "back");
                return true;
            }

            lastX = event.getX();
            lastY = event.getY();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            float deltaX = event.getX() - lastX;
            float deltaY = event.getY() - lastY;

            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                if (deltaX > 0 && direction != 2) direction = 3; // 右
                else if (deltaX < 0 && direction != 3) direction = 2; // 左
            } else {
                if (deltaY > 0 && direction != 0) direction = 1; // 下
                else if (deltaY < 0 && direction != 1) direction = 0; // 上
            }
        }
        return true;
    }


    private void stop(){

    }

    private void pause() {
        isRuning = false;
        handler.removeCallbacks(gameLoop);
    }


    private void restart() {
        score=0;
        second=0;
        init();
        handler.removeCallbacks(gameLoop);
        start();
        isGameOver=false;
        isRuning=true;
    }


    private void back() {
//        if (isRuning) {
//            return;
//        }

        Context context = getContext();
        Intent intent = new Intent(context, RankActivity.class);
        context.startActivity(intent);
    }


    public void start() {
        handler = new Handler();
        gameLoop = new Runnable() {
            @Override
            public void run() {
                if (!isGameOver) {
                    second += 250;
                    Log.d(TAG, second + "");
                    handler.postDelayed(this, 250); // 控制蛇的移动速度
                }
                moveSnake();
                invalidate();
            }
        };
        handler.post(gameLoop);
    }


    private void spawnFood() {
        Random random = new Random();
        int x, y;
//        boolean valid;
//        do {
        x = random.nextInt(NUM_CELLS_X);
        y = random.nextInt(NUM_CELLS_Y);
//            valid = true;
//        for (int[] part : snake) {
//            if (part[0] == x && part[1] == y) {
////                valid = false;
//                break;
//            }
//        }
//        } while (!valid);
        food = new int[]{x, y};
    }

    private void moveSnake() {
        int[] head = snake.get(0);
        int newX = head[0];
        int newY = head[1];

        switch (direction) {
            case 0:
                newY--;
                break; // 上
            case 1:
                newY++;
                break; // 下
            case 2:
                newX--;
                break; // 左
            case 3:
                newX++;
                break; // 右
        }

        if (newX < 0 || newY < 0 || newX >= NUM_CELLS_X || newY >= NUM_CELLS_Y) {
            isGameOver = true; // 撞到边界
            return;
        }

        for (int[] part : snake) {
            if (part[0] == newX && part[1] == newY) {
                isGameOver = true; // 撞到自己
                isRuning = false;
                return;
            }
        }

        snake.add(0, new int[]{newX, newY});

        if (newX == food[0] && newY == food[1]) {
            spawnFood(); // 吃到食物
            score++;
        } else {
            snake.remove(snake.size() - 1); // 移除尾部
        }
    }
}
